﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FTchina;
using System.Data;
using System.Collections;
using FTchina.Library;

public partial class UI_CallIn : System.Web.UI.Page
{
    string phone = string.Empty;
    Random r = new Random();
    string[] colors = { "#FFFFF4", "#F5FFE8", "#FFE6D9", "#F0FFF0", "#ECF5FF", "#FAF4FF" };//背景色
    public bool Sex = true;//前台判断是男是女


    protected void Page_Load(object sender, EventArgs e)
    {
 

        //if (basic.CheckFreshTime())
        //{//如果在登陆限定时间内，就伪造一个id，欺骗登录检查系统
        //    MasterHelper.MasterID = MD5MK.MD5String(FTchina.basic.GetGuid());
        //}
        //else
        //{//如果已经超时，就让重新登录
        //    Response.Redirect("/ui/login.aspx?title=登录超时！请重新登陆&returnpage=" + Request.RawUrl.ToString());
        //}

        

        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Expires = 0;
        Response.Buffer = true;
        Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
        Response.AddHeader("pragma", "no-cache");
        Response.CacheControl = "no-cache";


        phone = FTchina.basic.SafeRequest(Request["phone"]);

        if (MasterHelper.ClientType == "smsver")
        {
            Response.Redirect("/ui/Smsver/CallInSMSver.aspx?phone=" + phone);
        }

        
       
        if (!IsPostBack)
        {


            ReceiveCall(phone);
        }
    }





    /// <summary>
    /// 接收来电信息
    /// 新客户生成信息，老客户更新信息
    /// </summary>
    /// <param name="phone"></param>
    private void ReceiveCall(string phone)
    {
        GetUseadble();//获取可以预定的餐厅、房间
        litTargets.Text = phone;//显示来电号码


        string telphone = string.Empty;
        string landline = string.Empty;
        phone = FTchina.SMS.CustomerInfo.getFormatedPhone(phone, out telphone, out landline);
        txbCustomerTel0.Text = telphone;
        txbCustomerlandline0.Text = landline;
 


        litCustormInfo.Text = "新客户";
        if (phone.Length > 0 && FTchina.SMS.CustomerInfo.CheckCustomer(phone))
        {
            GetCustomerInfo(phone);//显示老客户的信息
        }
        

    }






    /// <summary>
    /// 获取用户信息，显示出来
    /// </summary>
    /// <param name="phone"></param>
    /// <returns></returns>
    private void GetCustomerInfo(string phone)
    {

        string CustomerInfo = "来电次数：{0}，预定次数：{1}，最后来电时间：{2}，最后预定时间：{3}";
        string id = FTchina.SMS.CustomerInfo.GetCustomerIDByPhone(phone).Trim();
        if (id.Length > 0)
        {
            FTchina.SMS.CustomerInfo.CallCountPlusOneBy(phone);//增加一次来电次数
            FTchina.Models.CustomerList mCustomerList = FTchina.BLL.CustomerListManager.GetCustomerListByid(Convert.ToInt32(id));
            litCustormInfo.Text = string.Format(CustomerInfo,
                mCustomerList.Callcount.ToString(),
                mCustomerList.MeetCount.ToString(),
                mCustomerList.LastCallDate.ToString("yyyy-MM-dd").Replace("1910-01-01", ""),
                mCustomerList.LastMeetDate.ToString("yyyy-MM-dd").Replace("1910-01-01", "")
                );
            txbcustomerName.Text = mCustomerList.CustomerName;
            txbCustomerTel0.Text = mCustomerList.CustomerTel0;
            txbCustomerlandline0.Text = mCustomerList.Customerlandline0;
            txbmemo.Text = mCustomerList.Memo;

            if (mCustomerList.CustormeSex == "女") Sex = false;//前台显示男女用
            //  ddlsex.SelectedValue = mCustomerList.CustormeSex;

            txbcustomerWork.Text = mCustomerList.CustomerWork;
            txbcustomerMeetAddress.Text = mCustomerList.CustomerMeetAddress;
            txbcustomerAddress0.Text = mCustomerList.CustomerAddress0;
            ddlcg.SelectedValue = mCustomerList.CustomerGroupID.ToString();
        }

    }



    /// <summary>
    /// 获取可以预定的餐桌、房间
    /// </summary>
    protected void GetUseadble()
    {
        string sql = "select * from CustomerGroup order by id asc";
        ddlcg.DataSource = FTchina.shujuku.GetDataTable(sql);
        ddlcg.DataTextField = "groupname";
        ddlcg.DataValueField = "id";
        ddlcg.DataBind();


        //改为前台页面调用方法加载
        //litDiningTable.Text = MakeCheckbox(colors[0], "早餐", shujuku.GetDataTable("select * from DinnerTableList where zaocustomerid='' order by DiningTableName desc "), "chkDiningTablezao", "DiningTableName");
        //litDiningTable.Text += MakeCheckbox(colors[1], "午餐", shujuku.GetDataTable("select * from DinnerTableList where zhongcustomerid='' order by DiningTableName desc "), "chkDiningTablezhong", "DiningTableName");
        //litDiningTable.Text += MakeCheckbox(colors[4], "晚餐", shujuku.GetDataTable("select * from DinnerTableList where wancustomerid='' order by DiningTableName desc "), "chkDiningTablewan", "DiningTableName");
        //litRoom.Text = MakeCheckbox(colors[3],"",shujuku.GetDataTable("select * from RoomList where state=0 order by RoomName asc"), "chkRoom", "RoomName");
    }





    /// <summary>
    /// 只获取时间输入那部分
    /// </summary>
    /// <param name="title"></param>
    /// <param name="type"></param>
    /// <param name="ChkId"></param>
    /// <param name="ChkValueField"></param>
    /// <returns></returns>
    public String GetDinnerUseableDate(string title, string type, string ChkId, string ChkValueField)
    {
        string tmp = string.Empty;
        string DateInput = "<b> " + title + "   到店时间<input type='text' id='txbdate{0}' name='txbdate{0}'    /><div   id='timer" + type + "' >速选：" + GetTimeLableByType(type) + "</b></div>";
        tmp = string.Format(DateInput, ChkId);
        return tmp;
    }

    /// <summary>
    /// 获取可以使用的楼层区域
    /// </summary>
    /// <param name="type"></param>
    /// <param name="ChkId"></param>
    /// <param name="ChkValueField"></param>
    /// <returns></returns>
    public String GetDinnerUseableArea(string type)
    {
        string tmp = string.Empty;
        tmp = "<b> " + GetAreaLable(type) + "</b>";

        return tmp;
    }




    /// <summary>
    /// 根据时间类型获取时间标签
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    private String GetTimeLableByType(string type)
    {
        string tmp = string.Empty;
        switch (type)
        {
            case "zao":
                tmp = GetTimeLable(6, 9);
                break;
            case "zhong":
                tmp = GetTimeLable(11, 14);
                break;
            case "wan":
                tmp = GetTimeLable(17, 20);
                break;
            default:
                tmp = GetTimeLable(6, 22);
                break;
        }

        return tmp;

    }

    /// <summary>
    /// 获取指定时间范围内的格式标签
    /// </summary>
    /// <param name="start"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    private String GetTimeLable(int start, int end)
    {
        string format = "<label>{0}</label>&nbsp;";
        string tmp = string.Empty;
        for (int i = start; i <= end; i++)
        {
            tmp += string.Format(format, i.ToString().PadLeft(2,'0') + ":00");
            tmp += string.Format(format, i.ToString().PadLeft(2, '0') + ":30");
        }
        return tmp;
    }
    /// <summary>
    /// 获取指定类型的区域位置
    /// </summary>
    /// <param name="start"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    private String GetAreaLable(string type)
    {
        string format = "<label>{0}</label>&nbsp;";
        string tmp = string.Empty;
        tmp += string.Format(format, "全部");
        if (type == "dinner")
        {//订餐
            DataTable dt = shujuku.GetDataTable("select * from arealist where type='floor' order by id desc");
            foreach (DataRow dr in dt.Rows)
            {
                tmp += string.Format(format, dr["areaname"]);

            }

        }

        return tmp;
    }

    /// <summary>
    /// 保存客户资料
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveCustomer_Click(object sender, EventArgs e)
    {
        string CustomerName = FTchina.basic.SafeRequest(txbcustomerName.Text);
        string CustormeSex = FTchina.basic.SafeRequest(Request["ddlsex"]);
        string CustomerGroupID = ddlcg.SelectedValue;
        string CustomerTel0 = FTchina.basic.SafeRequest(txbCustomerTel0.Text);
        string Customerlandline0 = FTchina.basic.SafeRequest(txbCustomerlandline0.Text);
        string CustomerWork = FTchina.basic.SafeRequest(txbcustomerWork.Text);
        string CustomerAddress0 = FTchina.basic.SafeRequest(txbcustomerAddress0.Text);
        string CustomerMeetAddress = FTchina.basic.SafeRequest(txbcustomerMeetAddress.Text);
        string Memo = FTchina.basic.SafeRequest(this.txbmemo.Text);
        string Nowdate = basic.GetSqliteDate();
        if (CustomerTel0.Trim().Length > 0)
        {
            if (!basic.ValidateMobile(CustomerTel0))
            {
                JS.Alert("手机号码输入错误！");
                return;
            }
        }
        SaveCustomerInfo(CustomerName, CustormeSex, CustomerGroupID, CustomerWork, CustomerTel0, Customerlandline0, CustomerAddress0, CustomerMeetAddress, Memo, Nowdate);
        CloseThis();
    }

    protected void btnok_Click(object sender, EventArgs e)
    {
        if (ChkSendSms.Checked)
        {
            if (txbSMS.Text.Trim().Length == 0)
            {
                JS.Alert("请输入短信内容！");
                return;
            }
        }



        string CustomerName = FTchina.basic.SafeRequest(txbcustomerName.Text);
        string CustormeSex = FTchina.basic.SafeRequest(Request["ddlsex"]);
        string CustomerGroupID = ddlcg.SelectedValue;
        string CustomerTel0 = FTchina.basic.SafeRequest(txbCustomerTel0.Text);
        string Customerlandline0 = FTchina.basic.SafeRequest(txbCustomerlandline0.Text);
        string CustomerWork = FTchina.basic.SafeRequest(txbcustomerWork.Text);
        string CustomerAddress0 = FTchina.basic.SafeRequest(txbcustomerAddress0.Text);
        string CustomerMeetAddress = FTchina.basic.SafeRequest(txbcustomerMeetAddress.Text);
        string zhongPcount = FTchina.basic.SafeRequest(txbzhongpcount.Text);
        string wanPcount = FTchina.basic.SafeRequest(txbwanpcount.Text);
        string zaoPcount = FTchina.basic.SafeRequest(txbzaopcount.Text);
        string Memo = FTchina.basic.SafeRequest(this.txbmemo.Text);
        string Nowdate = basic.GetSqliteDate();
        if (!basic.ValidateMobile(CustomerTel0))
        {
            JS.Alert("手机号码输入错误！");
            return;
        }
        if (zhongPcount.Length == 0) zhongPcount = "待定";
        if (wanPcount.Length == 0) wanPcount = "待定";
        if (zaoPcount.Length == 0) zaoPcount = "待定";

        /**
         * 1、如果客户是新客户，那么创建客户，如果是老客户，增加来电次数、更新来电时间
         * 2、插入一条预定记录，同时更新相关房间、餐桌的预定信息
         * 3、发送短信
         * */



        SaveCustomerInfo(CustomerName, CustormeSex, CustomerGroupID, CustomerWork, CustomerTel0, Customerlandline0, CustomerAddress0, CustomerMeetAddress, Memo, Nowdate);


        #region 插入订餐订房记录
        string DinnerZao = FTchina.basic.SafeRequest(Request.Form["chkDiningTablezao"]);
        string DinnerZhong = FTchina.basic.SafeRequest(Request.Form["chkDiningTablezhong"]);
        string DinnerWan = FTchina.basic.SafeRequest(Request.Form["chkDiningTablewan"]);
        string DinnerZaoDate = FTchina.basic.SafeRequest(Request.Form["txbdatechkDiningTablezao"]);
        string DinnerZhongDate = FTchina.basic.SafeRequest(Request.Form["txbdatechkDiningTablezhong"]);
        string DinnerWanDate = FTchina.basic.SafeRequest(Request.Form["txbdatechkDiningTablewan"]);



        //格式化为数据库识别的标准
        string Rdate = DateTime.Now.Date.ToString("yyyy-MM-dd") + " ";
        string Rzaodate = DateTime.Now.AddDays(1).Date.ToString("yyyy-MM-dd") + " ";//早上订餐是指前天订第二天早餐
        if (DinnerZaoDate.Length == 0)
        {
            DinnerZaoDate = DateTime.Now.ToString("s");
        }
        else
        {
            DinnerZaoDate = Rzaodate + DinnerZaoDate + ":00";

        }

        if (DinnerZhongDate.Length == 0)
        {
            DinnerZhongDate = Nowdate;
        }
        else
        {
            DinnerZhongDate = Rdate + DinnerZhongDate + ":00";

        }

        if (DinnerWanDate.Length == 0)
        {
            DinnerWanDate = Nowdate;
        }
        else
        {
            DinnerWanDate = Rdate + DinnerWanDate + ":00";
        }









        string CustomerID = FTchina.SMS.CustomerInfo.GetCustomerIDByPhone(CustomerTel0);
        if (CustomerID.Length == 0)
        {
            CustomerID = FTchina.SMS.CustomerInfo.GetCustomerIDByPhone(Customerlandline0);
        }

        //要先判断是否订餐订房
        //ctype=1 早餐，2午餐，3晚餐，4订房
        int ctype = 0;


        string ordersql = @"INSERT INTO [OrderList]
           ([CustomerID]
           ,[CType]
           ,[OrderDate]
           ,[OrderName]
            ,[pcount])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}'
           ,'{3}','{4}')";
        ArrayList al = new ArrayList();
        if (DinnerZao.Length > 0)
        {
            al.Add(string.Format(ordersql, CustomerID, 1, DinnerZaoDate, GetFormatNamesString(DinnerZao), zaoPcount));
            al.Add("update DinnerTableList set zaoCustomerID='" + CustomerID + "',zaoDate='" + DinnerZaoDate + "',zaocount='" + zaoPcount + "' where id in (" + GetFormatIdsString(DinnerZao) + ")");

        }
        if (DinnerZhong.Length > 0)
        {
            al.Add(string.Format(ordersql, CustomerID, 2, DinnerZhongDate, GetFormatNamesString(DinnerZhong), zhongPcount));
            al.Add("update DinnerTableList set zhongCustomerID='" + CustomerID + "',zhongDate='" + DinnerZhongDate + "',zhongcount='" + zhongPcount + "' where id in (" + GetFormatIdsString(DinnerZhong) + ")");

        } 
        if (DinnerWan.Length > 0)
        {
            al.Add(string.Format(ordersql, CustomerID, 3, DinnerWanDate, GetFormatNamesString(DinnerWan), wanPcount));
            al.Add("update DinnerTableList set wanCustomerID='" + CustomerID + "',wanDate='" + DinnerWanDate + "',wancount='" + wanPcount + "' where id in (" + GetFormatIdsString(DinnerWan) + ")");

        }
        
        shujuku.ExecuteSqlTransaction(al);




        #endregion


        #region 发送短信

        if (ChkSendSms.Checked & txbSMS.Text.Trim().Length > 0)
        {
            string content = txbSMS.Text;
            string Result = FTchina.SMSServer.SMSSender.Send2SeverWithLog(phone, content);
            if (!basic.ValidateMobile(phone))
            {
                JS.Alert("手机号码输入错误，短信未发送，详情查看短信发送日志！");

            }
            else
            {
                if (Result.Contains("成功"))
                {

                    JS.Alert("短信已发送，详情查看短信发送日志！");
                }
                else
                {
                    FTchina.JS.Alert("发送失败，请查看发送历史记录" + Result);
                }
            }


        }
        #endregion


        CloseThis();
    }


    /// <summary>
    /// 保存客户信息
    /// </summary>
    /// <param name="CustomerName"></param>
    /// <param name="CustormeSex"></param>
    /// <param name="CustomerGroupID"></param>
    /// <param name="CustomerTel0"></param>
    /// <param name="Customerlandline0"></param>
    /// <param name="CustomerAddress0"></param>
    /// <param name="CustomerMeetAddress"></param>
    /// <param name="Memo"></param>
    /// <param name="Nowdate"></param>
    private void SaveCustomerInfo(string CustomerName, string CustormeSex, string CustomerGroupID, string CustomerWork, string CustomerTel0, string Customerlandline0, string CustomerAddress0, string CustomerMeetAddress, string Memo, string Nowdate)
    {
        if (Customerlandline0.Length > 0)
        {//如果有固话，就赋值
            phone = Customerlandline0;
        }
        if (CustomerTel0.Length > 0)
        {//如果有手机，后赋值
            phone = CustomerTel0;
        }

        if (FTchina.SMS.CustomerInfo.CheckCustomer(phone))
        {//老用户

            //老客户更新资料，
            string sql = "update CustomerList set CustomerName='{0}',CustormeSex='{1}',CustomerGroupID='{2}',CustomerAddress0='{3}',CustomerMeetAddress='{4}',MeetCount=MeetCount+1,LastCallDate='{5}',LastMeetDate='{6}',CustomerTel0='{7}',Customerlandline0='{8}',CustomerWork='{9}',Memo='{11}' where CustomerTel0='{10}' or Customerlandline0='{10}' ";
            string execsql = string.Format(sql, CustomerName, CustormeSex,
                CustomerGroupID, CustomerAddress0, CustomerMeetAddress,
                Nowdate, Nowdate, CustomerTel0, Customerlandline0, CustomerWork,
                phone, Memo);
            shujuku.ExecuteSql(execsql);
        }
        else
        {//新用户
            string insertsql = @"INSERT INTO [CustomerList]
           ([CustomerName]
           ,[CustormeSex]
           ,[CustomerTel0]
           ,[Customerlandline0]         
           ,[CustomerAddress0]
           ,[CustomerMeetAddress]
           ,[Memo]
           ,[CustomerGroupID]
           ,[Callcount]
           ,[MeetCount]
           ,[LastCallDate]
           ,[LastMeetDate],[CustomerWork])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}'         
           ,'{3}'         
           ,'{4}'
           ,'{5}'
           ,'{6}'
           ,'1'
           ,'1'
           ,'{7}'
           ,'{8}'
           ,'{9}','{10}')";

            string execsql = string.Format(insertsql, CustomerName, CustormeSex, CustomerTel0, Customerlandline0, CustomerAddress0, CustomerMeetAddress,
                Memo, CustomerGroupID, Nowdate, Nowdate, CustomerWork);
            shujuku.ExecuteSql(execsql);
        }
    }


    /// <summary>
    /// 获取去除ID的餐厅名称或者房间名称
    /// </summary>
    /// <param name="names"></param>
    /// <returns></returns>
    protected string GetFormatNamesString(string names)
    {
        string tmp = string.Empty;
        foreach (string str in names.Split(','))
        {
            tmp += str.Split('-')[0]+",";
        }
        if (tmp.EndsWith(","))
        {
            tmp = tmp.Substring(0, tmp.Length - 1);
        }
        return tmp;
    }

    /// <summary>
    /// 获取去除名称的餐厅ID或者房间ID，适合直接作为in (id) 的sql语句
    /// </summary>
    /// <param name="names"></param>
    /// <returns></returns>
    protected string GetFormatIdsString(string names)
    {
        string tmp = string.Empty;
        foreach (string str in names.Split(','))
        {
            tmp += str.Split('-')[1]+",";
        }
        if (tmp.EndsWith(","))
        {
            tmp = tmp.Substring(0, tmp.Length - 1);
        }
        return tmp;
    }


    /// <summary>
    /// 获取格式化后的字符串
    /// </summary>
    /// <param name="names"></param>
    /// <returns></returns>
    protected string GetFormatString(string names)
    {
        DataTable dt = shujuku.GetDataTable("select * from arealist where type='floor' order by id desc");



        string tmp = string.Empty;
        string _tmpNameSingle = string.Empty;//临时存放去掉区域后的餐厅名称
        foreach (string str in names.Split(','))
        {
            foreach (DataRow dr in dt.Rows)
            {//循环比对，如果房间名称是以区域名称开始，那么截取后面的字符串就是房间的真实名称
                if (str.StartsWith(dr["areaname"].ToString().Trim()))
                {
                    _tmpNameSingle = str.Substring(dr["areaname"].ToString().Trim().Length, str.Length - dr["areaname"].ToString().Trim().Length);
                }

            }
            //格式化为适合 in（xx）的sql形式
            if (_tmpNameSingle.Trim().Length > 0)
            {
                tmp += "'" + _tmpNameSingle + "',";
            }
        }
        if (tmp.EndsWith(","))
        {
            tmp = tmp.Substring(0, tmp.Length - 1);
        }

        return tmp;

    }

    protected void CloseThis()
    {

        JS.Alert("操作成功");
        if (FTchina.basic.SafeRequest(Request["close"]).Length > 0)
        {
            JS.CloseWindow();
            JS.CloseOpenerWindow();
        }
        else
        {
            JS.JavaScriptLocationHref("/ui/welcome.aspx");

        }

    }





}